<template> 
  <div class="app-container">
    <!--隐藏或展开筛选条件-->
    <el-card class="operate-container" shadow="never">
      <i class="el-icon-tickets"></i>
      <span>筛选条件</span>
      <el-button
        class="btn-add"
        @click="changeFilterVisible()"
        size="mini">
        <div v-if="filterVisible">隐藏</div>
        <div v-else>展开</div>
      </el-button>
    </el-card>

     <!--筛选条件-->
    <el-card v-show="filterVisible" class="filter-container" shadow="never" >
      <el-row>
            <el-col :span="18"><i class="el-icon-search"></i><span>筛选搜索</span></el-col>
            <el-col :span="6">
              <el-button
                style="float: right"
                @click="handleSearchList()"
                type="primary"
                size="mini">
                查询结果
              </el-button>
             
              <el-button
                style="float: right;margin-right: 15px"
                @click="handleResetSearch()"
                size="mini">
                重置
              </el-button>
            </el-col>
      </el-row>
       <el-row>
          <el-col :span="24">
           <el-form :inline="true" label-position="right" :model="listQuery" :rules="listQueryRule" ref="listQueryRef" size="mini" label-width="140px">
              <el-form-item label="学科："  prop="subjectId" >
                <el-select v-model="listQuery.subjectId" placeholder="请选择学科" >
                  <el-option
                    v-for="item in subjectOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="阶段：" prop="level">
                <el-cascader v-model="listQuery.level"
                    :options="levelOptions"
                    :props="props"
                    collapse-tags
                    clearable></el-cascader>
              </el-form-item>
              <el-form-item label="题号搜索：" size="small" prop="questionIds" >
                <el-input  v-model="listQuery.questionIds"  placeholder="多个题号用逗号隔开，按照题号查询，其它条件忽略"></el-input>
              </el-form-item>

             

               <el-form-item label="题型："  prop="typeId" >
                <el-select v-model="listQuery.typeId" placeholder="全部"  >
                  <el-option
                    v-for="item in typeOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                  </el-option>
                </el-select>
              </el-form-item>
               <el-form-item label="难度：">
                <el-select v-model="listQuery.difStatus" placeholder="全部" clearable>
                  <el-option
                    v-for="item in difStatusOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                  </el-option>
                </el-select>
              </el-form-item>

              <el-form-item label="推荐程度：">
                <el-select v-model="listQuery.starStatus" placeholder="全部" clearable>
                  <el-option
                    v-for="item in starStatusOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                  </el-option>
                </el-select>
              </el-form-item>
              
              
              <el-form-item label="题目来源：">
                <el-select v-model="listQuery.sourceId" filterable placeholder="全部" clearable>
                  <el-option
                    v-for="item in sourceOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                  </el-option>
                </el-select>
              </el-form-item>
             <el-form-item label=" 题目附加说明：">
        
                  <el-input
                type="textarea"
                autosize
                placeholder="请输入内容"
                v-model="listQuery.cons">
              </el-input>
                 
            </el-form-item>
           
              <el-form-item label="做题情况：" v-if="isUser">
                <el-select   v-model="listQuery.testStatus" placeholder="全部" clearable>
                  <el-option
                    v-for="item in testStatusOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                  </el-option>
                </el-select>
                </el-form-item>
              
              
              <div v-else  >
                <el-form-item label="有效状态：">
                  <el-select v-model="listQuery.validStatus" placeholder="全部" >
                    <el-option
                      v-for="item in validStatusOptions"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value">
                    </el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="审核状态：">
                  <el-select v-model="listQuery.verifyStatus" placeholder="全部" >
                    <el-option
                      v-for="item in verifyStatusOptions"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value">
                    </el-option>
                  </el-select>
                </el-form-item>
             </div>
             
              <el-form-item label="知识点：" size="small"  style="width: 600px" >
                <el-input
                placeholder="输入关键字进行过滤"
                v-model="filterKnowledgeText">
                </el-input>
                <el-tree
                  :props="treeprops"
                  :data="knowledgeOptions"
                  v-model="listQuery.knowledge"
                  ref="mytree"
                  :expand-on-click-node="false"
                  node-key="id"
                  show-checkbox
                  :filter-node-method="filterKnowledgeNode"
                 >
                  <span class="custom-tree-node" slot-scope="{ node, data }">
                      <span style="font-size:12px">{{ node.label }}</span>
                      
                        </el-button>
                      </span>
                    </span>
                    </span>

                </el-tree>
                </el-form-item>
          
            </el-form>
          </el-col>
      </el-row>
    </el-card>
    
    <div class="table-container">
      <el-table ref="productTable"
                :data="list"
                style="width: 100%"
                @selection-change="handleSelectionChange"
                v-loading="listLoading"
                border>
        <el-table-column type="selection" width="60" align="center"></el-table-column>
        <el-table-column label="题号" width="100" align="center">
          <template slot-scope="scope">{{scope.row.id}}</template>
        </el-table-column>
        <el-table-column label="题目说明" width="120" align="center">
          <template slot-scope="scope">{{scope.row.comment}}</template>
        </el-table-column>
        <el-table-column label="学科" align="center">
          <template slot-scope="scope">{{scope.row.subjectId | optionFilter(subjectOptions)}}</template>
        </el-table-column>
       
        <el-table-column label="题型" width="140" align="center">
          <template slot-scope="scope">{{scope.row.typeId| optionFilter(allTypeOptions)}}</template>
        </el-table-column>
        <el-table-column label="难度" width="100" align="center">
          <template slot-scope="scope">{{scope.row.difStatus| optionFilter(difStatusOptions)}}</template>
        </el-table-column>
        <el-table-column label="推荐程度" width="100" align="center">
          <template slot-scope="scope">{{scope.row.starStatus | optionFilter(starStatusOptions)}}</template>
        </el-table-column>
        

        <el-table-column label="做题情况" width="100" align="center" v-if="isUser">
          <template slot-scope="scope">{{scope.row.testStatus| optionFilter(testStatusOptions)}}</template>
        </el-table-column>
        
        <el-table-column label="审核状态" width="100" align="center" v-if="!isUser">
            <template slot-scope="scope">
              <p>{{scope.row.verifyStatus | optionFilter(verifyStatusOptions)}}</p>
            </template>
        </el-table-column>
          <el-table-column label="有效性" width="100" align="center" v-if="!isUser">
            <template slot-scope="scope">{{scope.row.validStatus| optionFilter(validStatusOptions)}}</template>
          </el-table-column>
        
        <el-table-column label="操作" width="160" align="center">
          <template slot-scope="scope">
            <p>
              

              <el-button 
                size="mini"
                @click="handleShowQuestion(scope.$index, scope.row)">查看
              </el-button>
              <el-button v-if="isUser"
                size="mini"
                @click="showUpdateTestStatusDialog(scope.$index, scope.row)">做题情况修改
              </el-button>

              <el-button
                size="mini" v-if="isUser & scope.row.inlibrary" type="warning"
                @click="handleDeleteLibrary(scope.$index, scope.row)">出库
              </el-button>
              <el-button
                size="mini" v-if="isUser & !scope.row.inlibrary" type="primary"
                @click="handleAddLibrary(scope.$index, scope.row)">入库
              </el-button>

              <el-button v-if="!isUser"
                size="mini" 
                @click="handleUpdateQuestion(scope.$index, scope.row)">编辑
              </el-button>
            </p>
            <p>
              
              <el-button v-if="!isUser"
                size="mini"
                
                @click="handleDelete(scope.$index, scope.row)">删除
              </el-button>
            </p>
          </template>
        </el-table-column>
      </el-table>
    </div>
    
    <div class="batch-operate-container">
      <el-button  v-if="isUser"
        style="margin-left: 20px"
        class="search-button"
        @click="handleBatchAddLibray()"
        type="primary"
        size="mini">
        批量入库
      </el-button>

      <el-button v-if="isUser"
        style="margin-left: 20px"
        class="search-button"
        @click="handleBatchDeleteLibray()"
        type="warning"
        size="mini">
        批量出库
      </el-button>

      <el-button  v-if="!isUser"
        style="margin-left: 20px"
        class="search-button"
        @click="handleBatchVerify(1)"
        type="primary"
        size="mini">
        批量审核
      </el-button>

      <el-button  v-if="!isUser"
        style="margin-left: 20px"
        class="search-button"
        @click="handleBatchVerify(0)"
        type="warning"
        size="mini">
        批量取消审核
      </el-button>

       <el-button  v-if="!isUser"
        style="margin-left: 20px"
        class="search-button"
        @click="handleBatchValid(1)"
        type="primary"
        size="mini">
        批量有效
      </el-button>

      <el-button  v-if="!isUser"
        style="margin-left: 20px"
        class="search-button"
        @click="handleBatchValid(0)"
        type="warning"
        size="mini">
        批量无效
      </el-button>


    </div>
    <div class="pagination-container">
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        layout="total, sizes,prev, pager, next,jumper"
        :page-size="listQuery.pageSize"
        :page-sizes="[1,2,3]"
        :current-page.sync="listQuery.pageNum"
        :total="total">
      </el-pagination>
    </div>
     <el-dialog  width="80%" top="1vh"  title="修改做题情况" :visible.sync="updateTestStatusFormVisible" 
      :close-on-click-modal='false'>
          <span font-size="12px">用户名:{{this.name}}</span> 
          <br></br>
           <span font-size="12px">题号:{{this.updateTestStatusForm.id}}</span>     

        <el-form :model="updateTestStatusForm" inline ref="updateTestStatusFormRef" >
          
             

             <el-form-item label="做题情况：" v-if="isUser">
                <el-select   size="mini" v-model="updateTestStatusForm.testStatus" placeholder="全部" >
                  <el-option
                    v-for="item in testStatusOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                  </el-option>
                </el-select>
                </el-form-item>
           
          
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="updateTestStatusFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="handleUpdateTestStatus()">确 定</el-button>
        </div>
  </el-dialog>


    
  </div>
</template>
<script>
  import { mapGetters } from 'vuex'
  

  import {fetchList as fetchTypeList} from '@/api/type'
  import {fetchList as fetchSourceList} from '@/api/source'
  import { fetchList,deleteQuestion,updateTestStatus,updateVerifyStatus,updateValidStatus} from '@/api/question'
  import {fetchList as fetchKnowledgeList} from '@/api/knowledge'
  import {updateLibrary} from '@/api/useraction'
  import {deepClone} from '@/utils/helper';

  const defaultListQuery = {
   
    pageNum: 1,
    pageSize: 3,
    level:null,  //阶段
    knowledge:null,  //知识点
    questionIds:'', //题号；要是有多个题号用逗号隔开
    difStatus: null,  //难度
    starStatus: null,  //推荐指数
    subjectId: null,    //学科Id
    sourceId: null,    //题目来源Id
    cons:null, //题目附加说明
    typeId: null,    //题型
    //以下属性只有具体用户可以筛选
    testStatus: null,  //做题的状况

    //以下属性只有管理员才能筛选,默认只能选择审核通过并且有效的题目
    verifyStatus: 1, //审核状态
    validStatus: 1,  //有效状态

  };
  export default {
    name: "productList",
    data() {
       

      //学科自定义校验规则。如果题号为空，那么必须选择学科
      var checkSubjectIdRule = (rule, value, callback) => {
         
          if (this.listQuery.questionIds!=='') {
             callback();
          } else{
            if (!value) {
              return callback(new Error('请选择学科或直接输入题号'));
            }
            callback();
          }
        
      };
      //阶段自定义校验规则。如果题号为空，那么必须选择阶段
      var checkLevelRule = (rule, value, callback) => {
     
          if (this.listQuery.questionIds!=='') {
             callback();
          } else{
            if (!value) {
              return callback(new Error('请选择阶段或直接输入题号'));
            }
            callback();
          }
        
      };
      //阶段自定义校验规则。如果题号为空，那么必须选择阶段
      var checkQuestionIdsRule = (rule, value, callback) => {
        
          if (value!=='') {
            if(!/^\d+(,\d+)*$/.test(value)) {
               
                return callback(new Error('请输入数字题号中间用逗号隔开'));
            }
            
          } 
          callback();
         
        
      };
      return {
       
        listQuery: Object.assign({}, defaultListQuery),
        list: null,
        total: null,
        listLoading: false,
        //表格中多选的项目
        multipleSelection: [],
      

        //筛选框是否显示
        filterVisible:true,
        //自定义listQueryForm的校验规则

        listQueryRule :{
          subjectId: [
             { validator: checkSubjectIdRule, trigger: ['blur','change']},
          ],
          level: [
             { validator: checkLevelRule, trigger: ['blur','change']},
          ],
          questionIds: [
             { validator: checkQuestionIdsRule, trigger: 'blur' },
          ]
        },

        sourceOptions: [],//某一个学科下的试题来源和阶段下
        
        typeOptions:[], //某一个学科下所有题型
       
        
        //阶段状态的选项
        props: { multiple: true },

        knowledgeOptions:[], //某一学科下所有的知识点
        //知识点树的属性
        treeprops: {
              label: 'name',
              children: 'children',
              
        },
        filterKnowledgeText:null,
       


        updateTestStatusForm:{
          id:null,  //题号
          userid:this.userid ,//用户id
          testStatus:null //做题状态
        },
        updateTestStatusFormVisible:false,  //做题状态对话框是否可见
      }
    },
    computed:{
      ...mapGetters([
          'name',
          'subjectOptions',
          'allTypeOptions',
          'verifyStatusOptions',
          'leaveLevelOptions',
          'verifyStatusOptions',
          'levelOptions',
          'difStatusOptions',
          'validStatusOptions',
          'starStatusOptions',
          'testStatusOptions',
          'userid'
        ]),
      isUser(){
       
        return this.$store.getters.role===3
      },
    },
   
    filters: {
      optionFilter(value,options) {
        let res= options.find(function(x) {
          return x.value ===value;
          }
        )
        if (res){
          return res.label
        }else{
          return ''
        }
      },
    },
 
    methods: {
      handleResetSearch(){
        this.listQuery=Object.assign({}, defaultListQuery)
        this.knowledgeOptions=[]

      },
      filterKnowledgeNode(value, data) {
        if (!value) return true;
        
        return data.name.indexOf(value) !== -1;
      },

      handleUpdateQuestion(index,row){
        let routeData = this.$router.resolve({path:'/qms/questionUpdate',query:{id:row.id}});
        window.open(routeData.href, '_blank');

        //this.$router.push({path:'/qms/questionUpdate',query:{id:row.id}});
      },
      handleShowQuestion(index,row){
        let routeData = this.$router.resolve({path:'/qms/questionView',query:{id:row.id}});
        window.open(routeData.href, '_blank');

        this.$router.push({path:'/qms/questionView',query:{id:row.id}});
      },
      showUpdateTestStatusDialog(index,row){
        let routeData = this.$router.resolve({path:'/qms/testStatusUpdate',query:{id:row.id,testStatus:row.testStatus}});
        window.open(routeData.href, '_blank');

        //this.$router.push({path:'/qms/testStatusUpdate',query:{id:row.id,testStatus:row.testStatus}});
      },
     
      handleDelete(index,row){
        
        this.$confirm('再次确认删除该试题？', '提示', {
                  confirmButtonText: '确定',
                  cancelButtonText: '取消',
                  type: 'warning'
                }).then(() => {
                  deleteQuestion(row.id).then(response=>{

                    this.$message({
                          type: 'success',
                          message: '删除成功',
                          duration:1000
                      });

                    this.handleSearchList()

                  
                }).catch(error => {

                      this.$message({
                          type: 'error',
                          message: '删除失败',
                          duration:1000
                      });
              
                  });


                }).catch(() => {
                      
              
                 });

      },

      changeFilterVisible(){
          this.filterVisible=!this.filterVisible
      },
      subjectIdChanged(value){
       
        this.getTypeList(value);
        
        this.getSourceList(value,this.listQuery.level)
      },


      getTypeList(subjectId) {
        if (subjectId===null) return
        fetchTypeList({"subjectId":subjectId}).then(response => {
          this.typeOptions = [];
          let typeList = response.data.list;
          for (let i = 0; i < typeList.length; i++) {
            this.typeOptions.push({label: typeList[i].name, value: typeList[i].id});
          }
        });
      },

      

       //获得某个学科的试题来源
      getSourceList(subjectId,level) {
        if (level===null) return
        if (level.length===0) return
        if (subjectId===null) return
        let levelParams=[]

        for (let i = 0; i < level.length; i++) {
                levelParams.push(level[i][level[i].length-1]);
        }

        fetchSourceList({"subjectId":subjectId,"levelIds":levelParams.join(',')}).then(response => {
          this.sourceOptions = [];

          let sourceList = response.data.list;
          if (sourceList===null) return
          for (let i = 0; i < sourceList.length; i++) {
            this.sourceOptions.push({label: sourceList[i].name, value: sourceList[i].id});
          }
        });
      },


      //获得试题列表
      getList() {
        this.listLoading = true;
        this.listQuery.knowledge=this.$refs.mytree.getCheckedKeys(true)
        var submitParam=deepClone(this.listQuery)
        
        submitParam.knowledgeIds=submitParam.knowledge.join(',')
        let leaveLevels=[]
        let level=submitParam.level
        for (var i=0;i<level.length;i++){
              leaveLevels.push(level[i][level[i].length-1])
        }
        submitParam.levelIds=leaveLevels.join(',')
        delete submitParam.knowledge;
        delete submitParam.level;

        if (this.isUser){
          submitParam.userId=this.userid
        }

        fetchList(submitParam).then(response => {
          this.listLoading = false;
          this.list = response.data.list;
          this.total = response.data.total;
        });
      },

      checkItemSelected(){
        if(this.multipleSelection==null||this.multipleSelection.length<1){
          this.$message({
            message: '请选择要操作的题目',
            type: 'warning',
            duration: 1000
          });
          return false;
        }
        return true;
      },

      //批量审核试题
      handleBatchVerify(verified){
        if (this.checkItemSelected()){
           var message
           if (verified===1){
              message="是否要批量审核通过？"
            }else{
              message="是否要全部设为审核不通过？"
            }

           this.$confirm(message, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            let ids=[];
            for(let i=0;i<this.multipleSelection.length;i++){
              ids.push(this.multipleSelection[i].id);
            }
            let params={}
            params["ids"]=ids.join(",")
            params["verifyStatus"]=verified

            updateVerifyStatus(params).then(response=>{
              var replymessage
              if (verified===1){
                replymessage="批量审核成功"
              } else{
                replymessage="批量取消审核成功"
              }
                    
              this.$message({
                message: replymessage,
                type: 'success',
                duration: 1000
              });

                  
            }).catch(error => {
                console.log(error)
                      
              
            });
            this.handleSearchList()

          })

        }

      },


 //批量审核试题
      handleBatchValid(valid){
        if (this.checkItemSelected()){
           var message
           if (valid===1){
              message="是否要批量设为有效？"
            }else{
              message="是否要全部设为无效？"
            }

           this.$confirm(message, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            let ids=[];
            for(let i=0;i<this.multipleSelection.length;i++){
              ids.push(this.multipleSelection[i].id);
            }
            let params={}
            params["ids"]=ids.join(",")
            params["validStatus"]=valid

            updateValidStatus(params).then(response=>{
              var replymessage
              if (valid===1){
                replymessage="批量有效成功"
              } else{
                replymessage="批量无效成功"
              }
                    
              this.$message({
                message: replymessage,
                type: 'success',
                duration: 1000
              });
              this.handleSearchList()
                  
            }).catch(error => {
                console.log(error)
                      
              
            });
           

          })

        }

      },


      //批量入库操作
      handleBatchAddLibray(){
        if (this.checkItemSelected()){
           this.$confirm('是否要进行该批量入库?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            let ids=[];
            for(let i=0;i<this.multipleSelection.length;i++){
              ids.push(this.multipleSelection[i].id);
            }
            let params={}
            params["ids"]=ids.join(",")
            params["userId"]=this.userid
            params["inlibrary"]=1
            updateLibrary(params).then(response=>{

                    
              this.$message({
                message: '批量入库成功',
                type: 'success',
                duration: 1000
              });
              this.handleSearchList()
                  
            }).catch(error => {
                console.log(error)
                      
              
            });
           

          })

        }

      },
      //批量入库操作
      handleBatchDeleteLibray(){
        if (this.checkItemSelected()){
           this.$confirm('是否要进行该批量出库?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            let ids=[];
            for(let i=0;i<this.multipleSelection.length;i++){
              ids.push(this.multipleSelection[i].id);
            }
            let params={}
            params["ids"]=ids.join(",")
            params["userId"]=this.userid
            params["inlibrary"]=0

            updateLibrary(params).then(response=>{

                    
              this.$message({
                message: '批量出库成功',
                type: 'success',
                duration: 1000
              });
               this.handleSearchList()
                  
            }).catch(error => {
                console.log(error)
                      
              
            });
           

          })

        }

      },


     
     
      //点击“查询结果按钮”
      handleSearchList() {
        this.$refs.listQueryRef.validate(valid => {
          if (valid) {
            
            this.listQuery.pageNum = 1;
            this.getList();
          }
        })
      },
     
      handleSizeChange(val) {
        this.listQuery.pageNum = 1;
        this.listQuery.pageSize = val;
        this.getList();
      },
      handleCurrentChange(val) {
        this.listQuery.pageNum = val;
        this.getList();
      },
      handleSelectionChange(val) {
        this.multipleSelection = val;
      },
      handleAddLibrary(index,row){
        let params={}
        params["ids"]=[row.id].join(',')
        params["userId"]=this.userid
        params["inlibrary"]=1
        updateLibrary(params).then(response=>{

                    
              this.$message({
                message: '入库成功',
                type: 'success',
                duration: 1000
              });
              this.handleSearchList()
                  
            }).catch(error => {
                console.log(error)
                      
              
            })

      },
      handleDeleteLibrary(index,row){
        let params={}
        params["ids"]=[row.id].join(',')
        params["userId"]=this.userid
        params["inlibrary"]=0
        updateLibrary(params).then(response=>{

                    
              this.$message({
                message: '出库成功',
                type: 'success',
                duration: 1000
              });
              this.handleSearchList()
                  
            }).catch(error => {
                console.log(error)
                      
              
            })

      },
      getKnowledge(subjectId,level){
         if (level===null) return
         if (level.length===0) return
         if (subjectId===null) return
         let levelParams=[]

          for (let i = 0; i < level.length; i++) {
                levelParams.push(level[i][level[i].length-1]);
          }


          fetchKnowledgeList({"subjectId":subjectId,"levelIds":levelParams.join(',')}).then(response=>{
                  
            this.knowledgeOptions=response.data.list;
            
            if (this.listQuery.knowledge!=null)
              this.$refs.mytree.setCheckedKeys(this.listQuery.knowledge,true)
           
                

          }).catch(error=>{

              console.log(error)

           })


      },
    },
    watch: {
      filterKnowledgeText(val) {
        this.$refs.mytree.filter(val);
      },

      'listQuery.subjectId': function(newVal,oldVal){
        setTimeout(()=>{
         
          this.subjectIdChanged(newVal)
        },1000)

      },
      

      'listQuery.level': function(newVal,oldVal){
        setTimeout(()=>{
         
         this.getKnowledge(this.listQuery.subjectId,newVal)
         this.getSourceList(this.listQuery.subjectId,newVal)


        },1000)

      }

    },
  }
</script>



